﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace EngineOfEvermore.Common
{
    public sealed class TimeContext : IUpdateableTimeContext
    {
        #region struct ScheduledTask
        struct ScheduledTask
        {
            public ScheduledTask( float fireTime, Task task )
            {
                this.FireTime = fireTime;
                this.Task = task;
            }

            public readonly float FireTime;
            public readonly Task Task;
        }
        #endregion

        #region ScheduledTaskComparer
        sealed class ScheduledTaskComparer : Comparer<ScheduledTask>
        {
            public override int Compare( ScheduledTask x, ScheduledTask y )
            {
                return x.FireTime.CompareTo( y.FireTime );
            }
        }
        #endregion

        #region class TaskQueue
        sealed class TaskQueue
        {
            LinkedList<Task> _taskList = new LinkedList<Task>();

            public void Enqueue( Task task )
            {
                _taskList.AddLast( task );
            }

            public Task Dequeue()
            {
                Task first = _taskList.First.Value;
                _taskList.RemoveFirst();
                return first;
            }

            public void Remove( Task task )
            {
                _taskList.Remove( task );
            }

            public int Count
            {
                get { return _taskList.Count; }
            }

            public bool Contains( Task task )
            {
                return _taskList.Contains( task );
            }
        }
        #endregion

        #region Variables
        SortedList<int, List<Task>> _tasks = new SortedList<int, List<Task>>();
        bool _updating;
        float _currentTime;
        TaskQueue _tasksToBeAdded = new TaskQueue();
        TaskQueue _tasksToBeRemoved = new TaskQueue();
        BinaryHeap<ScheduledTask> _scheduledTasks = 
            new BinaryHeap<ScheduledTask>( new ScheduledTaskComparer() );
        #endregion

        #region Events
        public event Action PreUpdate;
        public event Action PostUpdate;
        #endregion

        #region Properties
        public bool IsUpdating
        {
            get { return _updating; }
        }

        public float CurrentTime
        {
            get { return _currentTime; }
        }
        #endregion

        #region Public Methods
        public void AddRepeatingTask( Task task )
        {
            Debug.Assert( !_tasksToBeAdded.Contains( task ) );
            Debug.Assert( !_tasksContains( task ) );

            if ( _updating )
            {
                _tasksToBeAdded.Enqueue( task );
            }
            else
            {
                _addTask( task );
            }

            if ( _tasksToBeRemoved.Contains( task ) )
            {
                _tasksToBeRemoved.Remove( task );
            }
        }

        public void RemoveRepeatingTask( Task task )
        {
            Debug.Assert( _tasksToBeAdded.Contains( task ) ^ _tasksContains( task ) );

            if ( !_tasksToBeAdded.Contains( task ) )
            {
                if ( _updating )
                {
                    _tasksToBeRemoved.Enqueue( task );
                }
                else
                {
                    _removeTask( task );
                }
            }
            else
            {
                _tasksToBeAdded.Remove( task );
            }
        }

        public void ScheduleOneTimeTask( float dt, Task task )
        {
            Debug.Assert( !_scheduledTasks.Any( st => st.Task == task ) );
            Debug.Assert( !_tasksContains( task ) );

            _scheduledTasks.Enqueue( new ScheduledTask( _currentTime + dt, task ) );
        }

        public void CancelOneTimeTask( Task task )
        {
            _scheduledTasks.RemoveAll( it => it.Task == task );
        }

        public bool IsOneTimeTaskPending( Task task )
        {
            return _scheduledTasks.Any( x => x.Task == task );
        }

        public void Update( LogicUpdateEventArgs e )
        {
            _currentTime += e.ElapsedTime;

            if ( this.PreUpdate != null )
            {
                this.PreUpdate();
            }

            while ( _scheduledTasks.Count != 0 && _currentTime >= _scheduledTasks.Peek().FireTime )
            {
                Task task = _scheduledTasks.Dequeue().Task;
                _addTask( task );
                _tasksToBeRemoved.Enqueue( task );
            }

            _updating = true;

            foreach ( KeyValuePair<int,List<Task>> list in _tasks )
            {
                foreach ( Task task in list.Value )
                {
                    task.Execute( e );
                }
            }

            _updating = false;

            while ( _tasksToBeAdded.Count != 0 )
            {
                _addTask( _tasksToBeAdded.Dequeue() );
            }

            while ( _tasksToBeRemoved.Count != 0 )
            {
                _removeTask( _tasksToBeRemoved.Dequeue() );
            }

            if ( this.PostUpdate != null )
            {
                this.PostUpdate();
            }
        }
        #endregion

        #region Private Methods
        void _addTask( Task task )
        {
            Debug.Assert( !_updating );

            List<Task> taskList;

            if ( !_tasks.TryGetValue( task.Priority, out taskList ) )
            {
                taskList = new List<Task>();
                _tasks.Add( task.Priority, taskList );
            }

            Debug.Assert( !taskList.Contains( task ) );

            taskList.Add( task );
        }

        void _removeTask( Task task )
        {
            Debug.Assert( !_updating );

            List<Task> taskList;

            if ( _tasks.TryGetValue( task.Priority, out taskList ) )
            {
                taskList.Remove( task );
            }
        }

        bool _tasksContains( Task task )
        {
            Debug.Assert( task != null );

            List<Task> taskList;

            if ( _tasks.TryGetValue( task.Priority, out taskList ) )
            {
                return taskList.Contains( task );
            }

            return false;
        }
        #endregion
    }

    #region Unit Tests
    #if ENGINE_OF_EVERMORE_ENABLE_UNIT_TESTS
    namespace UnitTest
    {
        using NUnit.Framework;

        [TestFixture]
        public class TimeContextTest
        {
            class TestTask : Task
            {
                Action<TestTask> _action;

                public TestTask( Action<TestTask> action, int priority ) :
                    base( priority )
                {
                    _action = action;
                }

                public override void Execute( LogicUpdateEventArgs e )
                {
                    if ( _action != null )
                    {
                        _action( this );
                    }
                }
            }

            [Test]
            public void TestRegularAddRegularRemove()
            {
                int taskExecuted = 0;
                TestTask task = new TestTask( ( (thisTask) => ++taskExecuted ), 10 );
                TimeContext timeContext = new TimeContext();

                timeContext.AddRepeatingTask( task );

                const int COUNT = 5;

                for ( int i = 0; i < COUNT; ++i )
                {
                    timeContext.Update( new LogicUpdateEventArgs() );
                    Assert.That( i + 1, Is.EqualTo( taskExecuted ) );
                }

                timeContext.RemoveRepeatingTask( task );

                for ( int i = 0; i < COUNT; ++i )
                {
                    timeContext.Update( new LogicUpdateEventArgs() );
                    Assert.That( COUNT, Is.EqualTo( taskExecuted ) );
                }
            }

            [Test]
            public void TestRegularAddInUpdateRemove()
            {
                int taskExecuted = 0;
                TimeContext timeContext = new TimeContext();

                Action<TestTask> action = delegate( TestTask thisTask ) 
                {
                    taskExecuted++;
                    if ( taskExecuted == 3 )
                    {
                        timeContext.RemoveRepeatingTask( thisTask );
                    }
                };

                TestTask task = new TestTask( action, 10 );
                
                timeContext.AddRepeatingTask( task );

                const int COUNT = 5;

                for ( int i = 0; i < COUNT; ++i )
                {
                    timeContext.Update( new LogicUpdateEventArgs() );
                }

                Assert.That( 3, Is.EqualTo( taskExecuted ) );

                for ( int i = 0; i < COUNT; ++i )
                {
                    timeContext.Update( new LogicUpdateEventArgs() );
                    Assert.That( 3, Is.EqualTo( taskExecuted ) );
                }
            }

            [Test]
            public void TestCurrentTime()
            {
                const float TIME_DELTA = 0.05f;
                const int UPDATE_COUNT = 1000;
                TimeContext tc = new TimeContext();

                ModifiableLogicUpdateEventArgs e = new ModifiableLogicUpdateEventArgs();
                e.SetElapsedTime( TIME_DELTA );

                for ( int i = 0; i < UPDATE_COUNT; ++i )
                {
                    float expectedCurrentTime = TIME_DELTA * i;

                    Assert.That( expectedCurrentTime.EpsilonEquals( tc.CurrentTime ) );

                    tc.Update( e );
                }
            }

            [Test]
            public void TestSchedule()
            {
                const float SCHEDULE_DELTA = 1.0f;
                const float UPDATE_DELTA = 0.7f;

                TimeContext tc = new TimeContext();

                bool taskExecuted = false;

                TestTask task = new TestTask( ( thisTask ) => taskExecuted = true, 10 );

                tc.ScheduleOneTimeTask( SCHEDULE_DELTA, task );

                var updateArgs = new ModifiableLogicUpdateEventArgs();
                updateArgs.SetElapsedTime( UPDATE_DELTA );

                tc.Update( updateArgs );

                Assert.That( taskExecuted, Is.False );
                Assert.That( tc.IsOneTimeTaskPending( task ) );

                tc.Update( updateArgs );

                Assert.That( taskExecuted );
                Assert.That( tc.IsOneTimeTaskPending( task ), Is.False );
            }

            [Test]
            public void TestMultipleSchedules()
            {
                const float SCHEDULE_DELTA = 1.0f;
                const float UPDATE_DELTA = 0.7f;
                const int SCHEDULE_COUNT = 10;
                const int UPDATE_COUNT = 20;

                TimeContext tc = new TimeContext();

                TestTask[] tasks = new TestTask[SCHEDULE_COUNT];
                bool[] taskExecuted = new bool[SCHEDULE_COUNT];

                for ( int i = 0; i < SCHEDULE_COUNT; ++i )
                {
                    // This creates a boxed copy of i
                    Object index = i;
                    tasks[i] = new TestTask( ( thisTask ) => taskExecuted[(int)index] = true, 10 );

                    tc.ScheduleOneTimeTask( SCHEDULE_DELTA * i, tasks[i] );
                }

                ModifiableLogicUpdateEventArgs e = new ModifiableLogicUpdateEventArgs();
                e.SetElapsedTime( UPDATE_DELTA );

                for ( int i = 0; i < UPDATE_COUNT; ++i )
                {
                    tc.Update( e );

                    for ( int j = 0; j < SCHEDULE_COUNT; ++j )
                    {
                        float fireTime = SCHEDULE_DELTA * j;

                        Assert.That( (fireTime <= tc.CurrentTime) == taskExecuted[j],
                            "Assertion failed for task " + j + " in update " + i );
                    }
                }
            }

            [Test]
            public void TestCancel()
            {
                const float SCHEDULE_DELTA = 1.0f;
                const float UPDATE_DELTA = 0.7f;
                const int SCHEDULE_COUNT = 10;
                const int UPDATE_COUNT = 20;
                const int TASKS_TO_CANCEL_COUNT = 5;

                TimeContext tc = new TimeContext();

                TestTask[] tasks = new TestTask[SCHEDULE_COUNT];
                bool[] taskExecuted = new bool[SCHEDULE_COUNT];

                for ( int i = 0; i < SCHEDULE_COUNT; ++i )
                {
                    // This creates a boxed copy of i
                    Object index = i;
                    tasks[i] = new TestTask( ( thisTask ) => taskExecuted[(int)index] = true, 10 );

                    tc.ScheduleOneTimeTask( SCHEDULE_DELTA * i, tasks[i] );
                }

                HashSet<int> cancelIndices = new HashSet<int>();
                Random r = new Random();

                while ( cancelIndices.Count < TASKS_TO_CANCEL_COUNT )
                {
                    cancelIndices.Add( r.Next( 0, SCHEDULE_COUNT ) );
                }

                foreach ( int index in cancelIndices )
                {
                    tc.CancelOneTimeTask( tasks[index] );
                }

                ModifiableLogicUpdateEventArgs e = new ModifiableLogicUpdateEventArgs();
                e.SetElapsedTime( UPDATE_DELTA );

                for ( int i = 0; i < UPDATE_COUNT; ++i )
                {
                    tc.Update( e );

                    for ( int j = 0; j < SCHEDULE_COUNT; ++j )
                    {
                        float fireTime = SCHEDULE_DELTA * j;

                        if ( cancelIndices.Contains( j ) )
                        {
                            Assert.That( taskExecuted[j], Is.False );
                        }
                        else
                        {
                            Assert.That( ( fireTime <= tc.CurrentTime ) == taskExecuted[j],
                                "Assertion failed for task " + j + " in update " + i );
                        }
                    }
                }
            }
        }
    }
    #endif

    #endregion
}
